import React, { useState, useRef, useEffect } from 'react'
import PropTypes from 'prop-types'

import { useDispatch, useSelector } from 'react-redux'
import todos from '../store/reducers/todos'
export default function Item({ todo }) {
  const refTxt = useRef(null)
  const dispatch = useDispatch()

  const [isEdit, setIsEdit] = useState(false)
  const [val, setVal] = useState(todo.name)
  // console.log(props, 7)
  useEffect(() => {
    refTxt.current.focus()
  }, [isEdit])
  return (
    <li className={isEdit ? 'editing' : ''}>
      <div className="view">
        <input
          className="toggle"
          type="checkbox"
          checked={todo.isDone}
          onChange={() => {
            console.log(todo.isDone)
            dispatch({
              type: 'todos/isDone',
              payload: {
                id: todo.id,
                isDone: !todo.isDone,
              },
            })
          }}
        />
        {/* 在name上双击，开启编辑模式：给li添加一个editing类 */}
        <label
          onDoubleClick={() => {
            // 1. 切换编辑状态 ===双击==显示点击的当前表单
            setIsEdit(true)
            // 表单聚焦
            console.log(refTxt.current, 12399)
            // 双击后的表单聚焦
            // refTxt.current.focus()
          }}
        >
          {todo.name}
        </label>
        <button
          className="destroy"
          onClick={() => {
            dispatch({
              type: 'todos/del',
              payload: todo.id,
            })
          }}
        />
      </div>
      <input
        ref={refTxt}
        className="edit"
        onBlur={() => {
          setIsEdit(false) // 关闭修改的表单
          // console.log(isEdit, 9911)
          /* 
        失去焦点
        + 获取表单值
        + 将值更新
        */
          dispatch({
            type: 'todos/edit',
            payload: {
              id: todo.id,
              name: val,
            },
          })
        }}
        value={val}
        onKeyUp={(e) => {}}
        onChange={(e) => {
          setVal(e.target.value)
          // console.log(e.target.value)
        }}
      />
    </li>
  )
}
Item.propTypes = {
  todo: PropTypes.object.isRequired,
}
